package com.ttdevs.es.service;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;

import com.ttdevs.util.BaseClass;

public class MainSensorManager extends BaseClass implements SensorEventListener {

	private SensorManager sensorManager;

	private long createTime;// 创建时间
	private long currentTime;// 当前时间，两个时间用于屏蔽启动时的距离感�?
	private float initLight;

	public MainSensorManager(Context context, Handler handler) {
		super(context, handler);
		this.sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
	}

	public void registerListener() {
		initLight = 0;
		currentTime = createTime = System.currentTimeMillis();

		if (getSPU().getLight()) {
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),
					SensorManager.SENSOR_DELAY_NORMAL);
		}
		if (getSPU().getProximity()) {
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
					SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	public void unregisterListener() {
		initLight = 0;
		currentTime = createTime = 0;
		sensorManager.unregisterListener(this);
	}

	// ***************SensorEventListener********************
	@Override
	public void onSensorChanged(SensorEvent event) {
		System.out.println("onSensorChanged:" + event.sensor.getName() + "|" + event.values[0]);

		int sensorType = event.sensor.getType();

		if (sensorType == Sensor.TYPE_PROXIMITY) {

			currentTime = System.currentTimeMillis();
			if (currentTime - createTime < INITDELAY) {
				System.out.println("延时期间，不处理距离变化");
				return;
			}

			sendAlarmMessage(PROXIMITY);
		}

		if ((sensorType == Sensor.TYPE_LIGHT)) {

			currentTime = System.currentTimeMillis();
			if (currentTime - createTime < INITDELAY) {
				System.out.println("延时期间不处理光照变�?..");
				return;
			}

			if (initLight == 0) { // 两次测试间隔在PROXIMITYDELAY毫秒以下
				initLight = event.values[0];
				return;
			}
			if (Math.abs(initLight - event.values[0]) > getSPU().getLightSensitivity()) {
				initLight = 0;
				sendAlarmMessage(LIGHT);
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		System.out.println("onAccuracyChanged:" + sensor.getName() + ":" + accuracy);
	}
}
